<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" th:replace="admin/layout/base :: html(~{::title}, ~{::#content}, ~{::script})">
<head>
    <title>订单管理 - 废物回收管理系统</title>
</head>
<body>
    <div id="content">
        <!-- 搜索栏 -->
        <div class="content-card mb-4">
            <form class="row g-3" id="searchForm">
                <div class="col-md-3">
                    <input type="text" class="form-control" id="keyword" placeholder="订单号/用户/回收员" name="keyword">
                </div>
                <div class="col-md-2">
                    <select class="form-select" id="status" name="status">
                        <option value="">全部状态</option>
                        <option value="PENDING">待处理</option>
                        <option value="PROCESSING">处理中</option>
                        <option value="COMPLETED">已完成</option>
                        <option value="CANCELLED">已取消</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <button type="submit" class="btn btn-primary">
                        <i class="bx bx-search"></i> 搜索
                    </button>
                </div>
                <div class="col-md-2 ms-auto">
                    <button type="button" class="btn btn-success" onclick="exportOrders()">
                        <i class="bx bx-export"></i> 导出订单
                    </button>
                </div>
            </form>
        </div>

        <!-- 数据表格 -->
        <div class="content-card">
            <div class="table-responsive">
                <table class="table table-hover" id="orderTable">
                    <thead>
                        <tr>
                            <th>订单号</th>
                            <th>用户</th>
                            <th>回收员</th>
                            <th>物品类型</th>
                            <th>重量(kg)</th>
                            <th>金额(元)</th>
                            <th>状态</th>
                            <th>创建时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- 数据将由JavaScript动态填充 -->
                    </tbody>
                </table>
            </div>
        </div>

        <!-- 分页 -->
        <div class="d-flex justify-content-between align-items-center mt-4">
            <div class="text-muted">
                共 <span id="totalCount">0</span> 条记录
            </div>
            <nav>
                <ul class="pagination mb-0">
                    <!-- 分页按钮将由JavaScript动态生成 -->
                </ul>
            </nav>
        </div>

        <!-- 订单详情模态框 -->
        <div class="modal fade" id="orderDetailModal" tabindex="-1" aria-labelledby="orderDetailModalLabel" aria-hidden="false">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="orderDetailModalLabel">订单详情</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
                    </div>
                    <div class="modal-body">
                        <div class="row g-4">
                            <!-- 基本信息 -->
                            <div class="col-md-6">
                                <div class="card h-100">
                                    <div class="card-header bg-light">
                                        <h6 class="mb-0">基本信息</h6>
                                    </div>
                                    <div class="card-body">
                                        <dl class="row mb-0">
                                            <dt class="col-sm-4">订单号</dt>
                                            <dd class="col-sm-8" id="detail-orderNo">-</dd>
                                            
                                            <dt class="col-sm-4">创建时间</dt>
                                            <dd class="col-sm-8" id="detail-createTime">-</dd>
                                            
                                            <dt class="col-sm-4">状态</dt>
                                            <dd class="col-sm-8" id="detail-status">-</dd>
                                            
                                            <dt class="col-sm-4">物品类型</dt>
                                            <dd class="col-sm-8" id="detail-itemType">-</dd>
                                            
                                            <dt class="col-sm-4">预估重量</dt>
                                            <dd class="col-sm-8" id="detail-estimatedWeight">-</dd>
                                            
                                            <dt class="col-sm-4">实际重量</dt>
                                            <dd class="col-sm-8" id="detail-actualWeight">-</dd>
                                            
                                            <dt class="col-sm-4">金额</dt>
                                            <dd class="col-sm-8" id="detail-price">-</dd>
                                        </dl>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- 用户信息 -->
                            <div class="col-md-6">
                                <div class="card h-100">
                                    <div class="card-header bg-light">
                                        <h6 class="mb-0">用户信息</h6>
                                    </div>
                                    <div class="card-body">
                                        <dl class="row mb-0">
                                            <dt class="col-sm-4">用户名</dt>
                                            <dd class="col-sm-8" id="detail-userName">-</dd>
                                            
                                            <dt class="col-sm-4">联系电话</dt>
                                            <dd class="col-sm-8" id="detail-userPhone">-</dd>
                                            
                                            <dt class="col-sm-4">地址</dt>
                                            <dd class="col-sm-8" id="detail-address">-</dd>
                                            
                                            <dt class="col-sm-4">回收员</dt>
                                            <dd class="col-sm-8" id="detail-collectorName">-</dd>
                                            
                                            <dt class="col-sm-4">回收员电话</dt>
                                            <dd class="col-sm-8" id="detail-collectorPhone">-</dd>
                                            
                                            <dt class="col-sm-4">评分</dt>
                                            <dd class="col-sm-8" id="detail-rating">-</dd>
                                            
                                            <dt class="col-sm-4">评价</dt>
                                            <dd class="col-sm-8" id="detail-comment">-</dd>
                                        </dl>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                    </div>
                </div>
            </div>
        </div>

        <style>
            /* 表格样式优化 */
            #orderTable {
                width: 100%;
                margin-bottom: 1rem;
                border-collapse: collapse;
            }

            #orderTable th {
                background-color: #f8f9fa;
                border-bottom: 2px solid #dee2e6;
                padding: 0.75rem;
                font-weight: 500;
                text-align: left;
                white-space: nowrap;
            }

            #orderTable td {
                padding: 0.75rem;
                vertical-align: middle;
                border-bottom: 1px solid #dee2e6;
            }

            #orderTable tbody tr:hover {
                background-color: rgba(0,0,0,.02);
            }

            #orderTable .badge {
                font-size: 0.875rem;
                padding: 0.35em 0.65em;
            }

            #orderTable .btn {
                margin-right: 0.25rem;
            }

            #orderTable .btn:last-child {
                margin-right: 0;
            }

            /* 订单详情模态框样式 */
            #orderDetailModal .modal-body {
                padding: 1.5rem;
            }
            
            #orderDetailModal .card {
                border: 1px solid rgba(0,0,0,.125);
                box-shadow: 0 0.125rem 0.25rem rgba(0,0,0,.075);
            }
            
            #orderDetailModal .card-header {
                background-color: #f8f9fa;
                border-bottom: 1px solid rgba(0,0,0,.125);
                padding: 0.75rem 1rem;
            }
            
            #orderDetailModal .card-body {
                padding: 1rem;
            }
            
            #orderDetailModal dl.row {
                margin-bottom: 0;
            }
            
            #orderDetailModal dt {
                color: #6c757d;
                font-weight: 500;
            }
            
            #orderDetailModal dd {
                margin-bottom: 0.5rem;
            }
        </style>
    </div>

    <!-- 必要的JavaScript依赖 -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.3.0/dist/sweetalert2.all.min.js"></script>
    
    <script th:fragment="script" type="text/javascript">
        // 显示错误信息
        function showError(message) {
            Swal.fire({
                icon: 'error',
                title: '错误',
                text: message
            });
        }

        // 加载订单列表
        function loadPage(page) {
            const keyword = $('#keyword').val();
            const status = $('#status').val();
            console.log('加载订单列表:', { keyword, status, page });
            
            $.ajax({
                url: `/admin/orders/data`,
                method: 'GET',
                data: {
                    keyword: keyword,
                    status: status,
                    page: page
                },
                success: function(response) {
                    console.log('订单数据:', response);
                    if (response.code === 200) {
                        const orders = response.data.content;
                        const totalPages = response.data.totalPages;
                        const totalElements = response.data.totalElements;
                        
                        updateTable(orders);
                        updatePagination(page, totalPages);
                        $('#totalCount').text(totalElements);
                    } else {
                        showError(response.message || '获取订单列表失败');
                    }
                },
                error: function(xhr) {
                    showError('获取订单列表失败: ' + (xhr.responseJSON?.message || '服务器错误'));
                }
            });
        }

        // 更新订单表格
        function updateTable(orders) {
            const tbody = $('#orderTable tbody');
            tbody.empty();
            
            if (!orders || orders.length === 0) {
                tbody.append('<tr><td colspan="9" class="text-center">暂无数据</td></tr>');
                return;
            }
            
            orders.forEach(order => {
                const tr = $('<tr>');
                tr.append(`<td>${order.orderNo || '-'}</td>`);
                tr.append(`<td>${order.userName || '-'} (${order.userRealName || '-'})</td>`);
                tr.append(`<td>${order.collectorName || '-'} (${order.collectorRealName || '-'})</td>`);
                tr.append(`<td>${order.itemType || '-'}</td>`);
                tr.append(`<td>${order.actualWeight || '0'}</td>`);
                tr.append(`<td>${order.price || '0'}</td>`);
                tr.append(`<td>${formatStatus(order.status)}</td>`);
                tr.append(`<td>${formatDateTime(order.createTime)}</td>`);
                
                const actions = [];
                actions.push(`<button class="btn btn-sm btn-info" onclick="viewOrder(${order.id})"><i class="bx bx-detail"></i> 详情</button>`);
                
                if (order.status === 'PENDING') {
                    actions.push(`<button class="btn btn-sm btn-danger" onclick="cancelOrder(${order.id})"><i class="bx bx-x"></i> 取消</button>`);
                }
                
                tr.append(`<td>${actions.join(' ')}</td>`);
                tbody.append(tr);
            });
        }

        // 更新分页
        function updatePagination(currentPage, totalPages) {
            const pagination = $('.pagination');
            pagination.empty();
            
            // 上一页
            pagination.append(`
                <li class="page-item ${currentPage === 0 ? 'disabled' : ''}">
                    <a class="page-link" href="javascript:void(0)" onclick="loadPage(${currentPage - 1})">
                        <i class="bx bx-chevron-left"></i>
                    </a>
                </li>
            `);
            
            // 页码
            for (let i = 0; i < totalPages; i++) {
                pagination.append(`
                    <li class="page-item ${currentPage === i ? 'active' : ''}">
                        <a class="page-link" href="javascript:void(0)" onclick="loadPage(${i})">${i + 1}</a>
                    </li>
                `);
            }
            
            // 下一页
            pagination.append(`
                <li class="page-item ${currentPage === totalPages - 1 ? 'disabled' : ''}">
                    <a class="page-link" href="javascript:void(0)" onclick="loadPage(${currentPage + 1})">
                        <i class="bx bx-chevron-right"></i>
                    </a>
                </li>
            `);
        }

        // 查看订单详情
        function viewOrder(id) {
            window.location.href = `/admin/orders/${id}`;
        }

        // 取消订单
        function cancelOrder(id) {
            Swal.fire({
                title: '确认取消订单?',
                text: "此操作不可撤销!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.post(`/admin/orders/${id}/cancel`)
                        .done(function() {
                            Swal.fire({
                                icon: 'success',
                                title: '订单已取消',
                                showConfirmButton: false,
                                timer: 1500
                            }).then(() => {
                                loadPage(0);
                            });
                        })
                        .fail(function(jqXHR) {
                            showError('取消订单失败: ' + (jqXHR.responseJSON?.message || '服务器错误'));
                        });
                }
            });
        }

        // 导出订单
        function exportOrders() {
            const keyword = $('#keyword').val();
            const status = $('#status').val();
            window.location.href = `/admin/orders/export?keyword=${keyword}&status=${status}`;
        }

        // 格式化状态
        function formatStatus(status) {
            const statusMap = {
                'PENDING': ['待处理', 'bg-warning'],
                'PROCESSING': ['处理中', 'bg-info'],
                'COMPLETED': ['已完成', 'bg-success'],
                'CANCELLED': ['已取消', 'bg-danger']
            };
            const [text, className] = statusMap[status] || ['未知', 'bg-secondary'];
            return `<span class="badge ${className}">${text}</span>`;
        }

        // 格式化日期时间
        function formatDateTime(dateTime) {
            if (!dateTime) return '-';
            return new Date(dateTime).toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: false
            });
        }

        // 当模态框关闭时，将焦点返回到触发按钮
        $('#orderDetailModal').on('hidden.bs.modal', function (e) {
            setTimeout(() => {
                $('button[title="查看详情"]').focus();
            }, 0);
        });

        // 初始化
        $(document).ready(function() {
            // 绑定搜索表单提交事件
            $('#searchForm').on('submit', function(e) {
                e.preventDefault();
                loadPage(0);
            });
            
            // 初始加载第一页数据
            loadPage(0);
        });
    </script>
</body>
</html> 